package net.atomarrow.render;

import java.io.IOException;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.atomarrow.ioc.ActionContext;

public class FreemarkerRender extends Render {
    public static final String TEMPLATE_NAME = "TEMPLATE_NAME";

    @Override
    public void render() {
        Configuration cfg = new Configuration();
        cfg.setNumberFormat("0.##");
        cfg.setDefaultEncoding("UTF-8"); 
        HttpServletRequest request = ActionContext.getContext().getRequest();
        cfg.setServletContextForTemplateLoading(request.getServletContext(), "/WEB-INF/ftls");
        Map<String,Object> root = new HashMap<String,Object>();
        Enumeration<String> attris = request.getServletContext().getAttributeNames();
        String key;
        Object value;
        while(attris.hasMoreElements()){
        	key = attris.nextElement();
        	value =request.getServletContext().getAttribute(key);
        	root.put(key, value);
        }
        attris = request.getSession().getAttributeNames();
        while(attris.hasMoreElements()){
        	key = attris.nextElement();
        	value =request.getSession().getAttribute(key);
        	root.put(key, value);
        }
        attris = request.getAttributeNames();
        while(attris.hasMoreElements()){
            key = attris.nextElement();
            value =request.getAttribute(key);
            root.put(key, value);
        }
        try {
            Template t = cfg.getTemplate(getAttr(TEMPLATE_NAME) +".ftl","UTF-8");
            HttpServletResponse response = ActionContext.getContext().getResponse();
            response.setContentType("text/html;charset=UTF-8");
            Writer out = response.getWriter();
            t.process(root, out); 
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
